<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 3月30日
 * Time: 10:05
 */
namespace app\Api\controller;

use app\api\model\DotiappData;
use app\api\controller\Offer;

class Dotiapp
{
    private $sid = 107456;
    private $token = 505606;

    public function index()
    {
        $sid = 107456;
        $token = 505606;
        $limit = 10;
        $get_url = 'http://ads.ikmytech.com/afs.do?sid='.$sid.'&token='.$token.'&cat=1&adn='.$limit.'&os=0';


        $get_str = file_get_contents($get_url);
        $get_content = json_decode($get_str,true);
        dump($get_content);
    }

    /*
     * 获取offer数据
     */
    public function getData()
    {
        $data_mod = new DotiappData;

        $limit = 500;//获取条数
        $url = 'http://ads.ikmytech.com/afs.do?sid='.$this->sid.'&token='.$this->token.'&cat=1&adn='.$limit.'&os=0';

        set_time_limit(0);
        echo '开始:'.date("H:i:s")."<br />";
        $get_str = file_get_contents($url);
        $get_content = json_decode($get_str,true);//dump($get_content);exit;
        echo '获取数据：'.date("H:i:s")."<br />";

        $i = $j = $m = 0;
        $new_offerids = $update_offerids = '';
        $all_offerids = $update_data = $insert_data = array();

        if(!empty($get_content['ads'])){
            $data_arr = $get_content['ads'];
            if(!empty($data_arr)){
                //轮询所有数据
                foreach($data_arr as $k=>$v){

                    //0.2以下的单子不导入
                    if($v['price'] < 1.5) {
                        continue;
                    }

                    $all_offerids[] = $v['ad_id'];


                    $v['preview_url'] = ($v['os'] == 0 && !empty($v['pkg'])) ? 'https://itunes.apple.com/cn/app/id'.$v['pkg'] : '';


                    $v['min_os'] = format_ver($v['min_os']);

                    $offer_info = $data_mod->find($v['ad_id']);
                    if(!empty($offer_info)){ //该offer已经存在,对比信息是否有更新
                        $diff_arr = array();
                        $offer_info = $offer_info->toArray();

                        if($offer_info['price'] != $v['price']){ //如果价格有更新，则获取更新数据
                            $diff_arr['update_time'] = time();
                            $diff_arr['ad_id'] = $v['ad_id'];
                            $diff_arr['price'] = $v['price'];
                            $diff_arr['offer_status'] = 2;// 2表示等待更新
                            $update_data[] = $diff_arr;
                            $i++;//更新数
                            $update_offerids .= $v['ad_id'].',';//记录日志用的
                        } else {
                            $j++;//已有数
                        }


                    } else { //该offer不存在,获取新增数据
                        $time = time();
                        $v['update_time'] = $time;
                        $v['create_time'] = $time;
                        $insert_data[] = $v;

                        $new_offerids .=$v['ad_id'].',';//记录日志用的

                        $m++;//新增数
                    }
                }
            }
        }

        echo '循环数据：'.date("H:i:s")."<br />";
        //新增记录

        if(!empty($insert_data))
        {
            $insert_res = $data_mod->saveAll($insert_data,false);
        }

        //更新记录
        if(!empty($update_data))
        {
            $update_res = $data_mod->isUpdate()->saveAll($update_data);
        }


        //将本次没有获取的单子全部做下线处理
        $data_mod->whereNotIn('ad_id',$all_offerids)->where(array('offer_status'=>1))->update(array('update_time'=> time(),'offer_status'=> 3));
        //记录日志
        save_apilog('add_offersId:'.$new_offerids,'dotiapp');
        save_apilog('update_offersId:'.$update_offerids,'dotiapp');

        echo '插入数据：'.date("H:i:s")."<br />";

        echo '更新数据:'.$i."<br />";
        echo '已有数据:'.$j."<br />";
        echo '新增数据:'.$m."<br />";
    }

    /*
     * 推送offer
     */
    public function postOffer()
    {
        $offer_obj = new Offer();
        $advertiser_id = 126;
        $data_mod = new DotiappData;


        //$info = $data_mod->limit(1)->find()->toArray();
        $insert_data = $data_mod->where(array('offer_id'=>0,'offer_status'=>0))->select()->toArray();
        //dump($insert_data);exit;
        if(empty($insert_data))
        {
            echo 'No offers add';
            exit;
        }
        foreach($insert_data as $info){
            //0.2以下的单子不导入
            /*if($info['price'] < 0.2) {
                continue;
            }*/

            $os = $info['os'] == 'ios' ? 0 : 1;
            $osv = $info['min_os'];
            if($os == 0)//ios系统
            {
                $destination_url = $info['click_url'].'&os=0&osv='.$osv.'&idfa={ios_idfa}&pb={click_id}&subid={aff_id}';
            } else {//android系统
                $destination_url = $info['click_url'].'&os=1&osv='.$osv.'&udid={android_id}&gaid={google_aid}&pb={click_id}&subid={aff_id}';
            }

            $countries = explode(',',$info['c2code']);
            $os_version = empty($info['min_os']) ? 0 : (($info['os'] == 0 && $info['min_os'] < 5.0) ? 0 : $info['min_os']);

            $param = array(
                'name' => $info['title'],
                'preview_url' => empty($info['preview_url']) ? '' : $info['preview_url'],
                //'destination_url' => 'http://ads.dofunapps.com/acs.php?sid=6362&adid=7792014',
                'destination_url' => $destination_url,
                'description' => '',
                'offer_id' => $info['ad_id'],//这个offer id是上游给的单子的offer id
                'price' => $info['price'],
                'os' => $info['os'],
                'os_version' => $os_version,
                'country' => $countries,
                'day_cap' => 1000,
                'status' => 1,
            );
            $res = $offer_obj->addOffer($param,$advertiser_id);
            //dump($res);
            if($res['code'] != 0){
                save_apilog('post_fail:'.json_encode($res),'dotiapp');
                continue;
            }
            //dump($param);dump($res);exit;
            //dump($res);
            $update_data = array('offer_id'=> $res['data']['offer']['id'],'offer_status'=> 1);
            //$data_mod->save($update_data,array('id'=> $info['id']));
            $data_mod->where(array('ad_id'=> $info['ad_id']))->update($update_data);
        }
        //dump($info);



    }

    /*
     * 更新offer
     */
    public function updateOffer()
    {
        $offer_obj = new Offer();
        $advertiser_id = 126;
        $data_mod = new DotiappData;
        $update_data = array();

        $update_offerid_list = $data_mod->where(array('offer_id'=>array('>',0),'offer_status'=>2))->field('ad_id,price,offer_id')->select()->toArray();//dump($update_offerid_list);exit;

        if(empty($update_offerid_list))
        {
            echo 'No offers update';
            exit;
        }
        foreach($update_offerid_list as $info){

            $offer_res = $offer_obj->updateOfferPrice($info['offer_id'],$info['price']);
            if($offer_res['code'] != 0)
            {
                save_apilog('update_offer_price:'.json_encode($offer_res),'dotiapp');
            }
            //dump($res);
            $update_data[] = array('ad_id'=> $info['ad_id'],'offer_status'=> 1);
        }
        //dump($info);


        $res = $data_mod->isUpdate()->saveAll($update_data);

    }

    /*
     * 更新offer状态
     */
    public function updateOfferStatus()
    {
        //$ids = array(127);
        $offer_obj = new Offer();

        $data_mod = new DotiappData;
        //将单子下线
        $where = array(
            'offer_status'=> 3,
        );
        $list = $data_mod->field('offer_id')->where($where)->limit(100)->select()->toArray();
        $ids = array();
        foreach($list as $id){
            $ids[] = $id['offer_id'];
        }
        if(!empty($ids)){
            $res = $offer_obj->pausedOffer($ids);
            if($res['code'] != 0){
                save_apilog('paused_offer:'.json_encode($res),'dotiapp');
            }
            $data_mod->whereIn('offer_id',$ids)->update(array('offer_status'=> -1));
        }


    }
}